package lbs

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"sort"
	"strings"
)

func (q *QQLbsClient) fieldToString(v interface{}) string {
	t := ""
	switch v.(type) {
	case string:
		t = v.(string)
	case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
		t = fmt.Sprintf("%v", v)
	case bool:
		if v.(bool) {
			t = "true"
		} else {
			t = "false"
		}
	case float32, float64:
		t = fmt.Sprintf("%v", v)
	default:
		b, err := json.Marshal(v)
		if err != nil {
			t = ""
		}
		t = string(b)
	}
	return t
}

func (q *QQLbsClient) _genSortStr(param map[string]interface{}) string {
	keys := make([]string, 0, len(param))
	for k := range param {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	var res []string
	for _, k := range keys {
		if strings.ToLower(k) == "sig" {
			continue
		}
		t := q.fieldToString(param[k])
		if t != "" {
			res = append(res, fmt.Sprintf("%s=%s", k, t))
		}
	}
	return strings.Join(res, "&")
}

func (q *QQLbsClient) _md5(str string) string {
	return strings.ToLower(fmt.Sprintf("%x", md5.Sum([]byte(str))))
}

// Sign 请求签名
func (q *QQLbsClient) Sign(api, secret string, param map[string]interface{}) string {
	// 生成字典序字符串
	sortStr := q._genSortStr(param)
	//  请求路径+”?”+请求参数+SK进行拼接，并计算拼接后字符串md5值（字符必须为小写），即为签名(sig)：
	signStr := fmt.Sprintf("%s?%s%s", api, sortStr, secret)
	// 生成签名
	return q._md5(signStr)
}
